<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>欢迎使用知识库应用</title>
    <link href="https://unpkg.com/tailwindcss@2.2.19/dist/tailwind.min.css" rel="stylesheet">
    <link rel="preload" href="https://unpkg.com/tailwindcss@2.2.19/dist/tailwind.min.css" as="style">
    <link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
    <style>
        /* 基础样式备份 */
        body {
            background-color: #f3f4f6;
            margin: 0;
            padding: 0;
            font-family: system-ui, -apple-system, sans-serif;
        }
        .container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 2rem 1rem;
        }
        textarea, button, input {
            font-family: inherit;
        }
        .hidden {
            display: none;
        }
        /* 思考过程折叠区域样式 */
        .thinking-details summary {
            list-style: none;
            position: relative;
            padding-left: 1.5rem;
        }
        .thinking-details summary::-webkit-details-marker {
            display: none;
        }
        .thinking-details summary::before {
            content: '▶';
            position: absolute;
            left: 0;
            transform: translateY(-2px);
            transition: transform 0.2s;
        }
        .thinking-details[open] summary::before {
            transform: rotate(90deg) translateX(-2px);
        }
    </style>
</head>
<body class="bg-gray-100 min-h-screen">
    <div class="container mx-auto px-4 py-8">
        <h1 class="text-3xl font-bold text-center mb-8 text-gray-800">欢迎使用知识库应用</h1>
        
        <div class="max-w-3xl mx-auto">
            <!-- 文件上传部分 -->
            <div class="bg-white rounded-lg shadow-md p-6 mb-6">
                <h2 class="text-xl font-semibold mb-4 text-gray-800">上传文档</h2>
                <div class="flex flex-col gap-4">
                    <div class="flex items-center gap-4">
                        <input type="file" 
                               id="fileInput" 
                               class="hidden" 
                               accept=".txt,.pdf,.doc,.docx">
                        <button onclick="document.getElementById('fileInput').click()" 
                                class="px-4 py-2 bg-gray-500 text-white rounded-lg hover:bg-gray-600 focus:outline-none focus:ring-2 focus:ring-gray-500">
                            选择文件
                        </button>
                        <span id="fileName" class="text-gray-600">未选择文件</span>
                    </div>
                    <button onclick="uploadFile()" 
                            id="uploadButton"
                            class="px-6 py-2 bg-green-500 text-white rounded-lg hover:bg-green-600 focus:outline-none focus:ring-2 focus:ring-green-500 disabled:opacity-50 disabled:cursor-not-allowed"
                            disabled>
                        上传文档
                    </button>
                    <div id="uploadStatus" class="text-sm"></div>
                </div>
            </div>

            <!-- 搜索框部分 -->
            <div class="bg-white rounded-lg shadow-md p-6">
                <div class="flex flex-col gap-4">
                    <textarea 
                        id="searchInput" 
                        class="w-full px-4 py-3 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 resize-none"
                        rows="4"
                        placeholder="请输入您的问题..."
                        style="min-height: 120px;"
                    ></textarea>
                    <button onclick="search()" 
                            class="px-6 py-3 bg-blue-500 text-white rounded-lg hover:bg-blue-600 focus:outline-none focus:ring-2 focus:ring-blue-500">
                        搜索
                    </button>
                </div>
            </div>

            <div id="results" class="mt-8 space-y-4">
                <!-- 搜索结果将在这里动态显示 -->
            </div>

            <div id="loading" class="hidden text-center py-4">
                <div class="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-500 mx-auto"></div>
            </div>
        </div>
    </div>

    <noscript>
        <style>
            .js-only { display: none; }
        </style>
        <div class="text-center text-red-500 p-4">
            请启用 JavaScript 以获得完整的功能体验
        </div>
    </noscript>

    <script>
        // 将函数定义移到全局作用域
        async function uploadFile() {
            const fileInput = document.getElementById('fileInput');
            const uploadStatus = document.getElementById('uploadStatus');
            const uploadButton = document.getElementById('uploadButton');
            
            if (!fileInput.files.length) return;
            
            const formData = new FormData();
            formData.append('file', fileInput.files[0]);
            
            uploadButton.disabled = true;
            uploadStatus.innerHTML = '<div class="text-blue-500">文档上传处理中...</div>';
            
            try {
                const response = await fetch('/upload', {
                    method: 'POST',
                    body: formData
                });
                
                const data = await response.json();
                
                if (data.success) {
                    uploadStatus.innerHTML = `<div class="text-green-500">${data.message}</div>`;
                    fileInput.value = '';
                    document.getElementById('fileName').textContent = '未选择文件';
                } else {
                    uploadStatus.innerHTML = `<div class="text-red-500">上传失败: ${data.error}</div>`;
                }
            } catch (error) {
                uploadStatus.innerHTML = `<div class="text-red-500">上传出错: ${error.message}</div>`;
            } finally {
                uploadButton.disabled = false;
            }
        }

        async function search() {
            const query = document.getElementById('searchInput').value;
            if (!query.trim()) return;

            const loading = document.getElementById('loading');
            const results = document.getElementById('results');
            
            loading.classList.remove('hidden');
            results.innerHTML = '';

            try {
                const response = await fetch('/search', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({ query })
                });

                const data = await response.json();
                
                if (data.success) {
                    let htmlContent = '';
                    
                    // 显示 AI 思考过程（如果有）- 使用可折叠区域
                    if (data.thinking) {
                        // 使用DOM API创建思考过程元素，避免模板字符串中的空格问题
                        const thinkingDiv = document.createElement('div');
                        thinkingDiv.className = 'bg-yellow-50 rounded-lg shadow-md p-6 mb-6';
                        
                        const detailsElem = document.createElement('details');
                        detailsElem.className = 'thinking-details';
                        
                        const summaryElem = document.createElement('summary');
                        summaryElem.className = 'text-xl font-semibold mb-2 text-yellow-800 cursor-pointer hover:text-yellow-600';
                        summaryElem.textContent = 'AI 思考过程 (点击展开/折叠)';
                        
                        const contentDiv = document.createElement('div');
                        contentDiv.className = 'text-gray-700 whitespace-pre-wrap prose mt-3 pl-2 border-l-2 border-yellow-300';
                        contentDiv.textContent = data.thinking;
                        
                        detailsElem.appendChild(summaryElem);
                        detailsElem.appendChild(contentDiv);
                        thinkingDiv.appendChild(detailsElem);
                        
                        const tempContainer = document.createElement('div');
                        tempContainer.appendChild(thinkingDiv);
                        htmlContent += tempContainer.innerHTML;
                    }
                    
                    // 显示 AI 最终答案
                    if (data.answer) {
                        // 使用不保留空格的方式构建HTML
                        const answerDiv = document.createElement('div');
                        answerDiv.className = 'bg-green-50 rounded-lg shadow-md p-6 mb-6';
                        
                        const titleH2 = document.createElement('h2');
                        titleH2.className = 'text-xl font-semibold mb-2 text-green-600';
                        titleH2.textContent = 'AI 回答';
                        
                        const contentDiv = document.createElement('div');
                        contentDiv.className = 'text-gray-700 prose';
                        contentDiv.textContent = data.answer;
                        
                        answerDiv.appendChild(titleH2);
                        answerDiv.appendChild(contentDiv);
                        
                        // 将创建的DOM元素转换为HTML字符串
                        const tempContainer = document.createElement('div');
                        tempContainer.appendChild(answerDiv);
                        htmlContent += tempContainer.innerHTML;
                    }

                    // 显示相关文档
                    if (data.results && data.results.length > 0) {
                        // 使用DOM API创建相关文档元素
                        const docsDiv = document.createElement('div');
                        docsDiv.className = 'bg-white rounded-lg shadow-md p-6';
                        
                        const titleH2 = document.createElement('h2');
                        titleH2.className = 'text-xl font-semibold mb-4 text-gray-800';
                        titleH2.textContent = '参考文档';
                        docsDiv.appendChild(titleH2);
                        
                        data.results.forEach(result => {
                            const resultDiv = document.createElement('div');
                            resultDiv.className = 'mb-4 last:mb-0 p-4 bg-gray-50 rounded';
                            
                            const textDiv = document.createElement('div');
                            textDiv.className = 'text-gray-600';
                            textDiv.textContent = result.text;
                            
                            const scoreDiv = document.createElement('div');
                            scoreDiv.className = 'mt-2 text-sm text-gray-500';
                            scoreDiv.textContent = `相关度: ${Math.round(result.score * 100)}%`;
                            
                            resultDiv.appendChild(textDiv);
                            resultDiv.appendChild(scoreDiv);
                            docsDiv.appendChild(resultDiv);
                        });
                        
                        const tempContainer = document.createElement('div');
                        tempContainer.appendChild(docsDiv);
                        htmlContent += tempContainer.innerHTML;
                    } else {
                        const noDocsDiv = document.createElement('div');
                        noDocsDiv.className = 'text-center text-gray-500';
                        noDocsDiv.textContent = '未找到相关参考文档';
                        
                        const tempContainer = document.createElement('div');
                        tempContainer.appendChild(noDocsDiv);
                        htmlContent += tempContainer.innerHTML;
                    }

                    results.innerHTML = htmlContent;
                } else {
                    results.innerHTML = `<div class="text-center text-red-500">搜索出错: ${data.error}</div>`;
                }
            } catch (error) {
                results.innerHTML = `<div class="text-center text-red-500">请求失败: ${error.message}</div>`;
            } finally {
                loading.classList.add('hidden');
            }
        }

        // DOM 加载完成后的初始化代码
        document.addEventListener('DOMContentLoaded', function() {
            // 文件上传相关的事件监听
            document.getElementById('fileInput').addEventListener('change', function(e) {
                const fileName = e.target.files[0]?.name || '未选择文件';
                document.getElementById('fileName').textContent = fileName;
                document.getElementById('uploadButton').disabled = !e.target.files.length;
            });

            // 添加回车键搜索功能
            document.getElementById('searchInput').addEventListener('keypress', function(e) {
                if (e.key === 'Enter') {
                    search();
                }
            });
        });
    </script>
</body>
</html> 